const { Service } = require('egg');

class UserService extends Service {
    /**
     * 根据用户名获取用户信息
     * @param {string} username 用户名
     */
    async findByUsername(username) {
        let sql = 'select * from user where username = ? limit 0, 1';
        let params = [username];
        let res = await this.app.mysql.query(sql, params);
        return res[0];
    }

    /**
     * 添加用户
     * @param {object} user 用户基本信息
     */
    async create(user) {
        const { username, password, nickname } = user;
        let sql =
            'insert into user (username, password, nickname) values (?, ?, ?)';
        let params = [username, password, nickname];
        let res = await this.app.mysql.query(sql, params);
        return res;
    }

    /**
     * 根据用户id，获取用户的权限（前端路由）
     * @param {number} uid 用户id
     */
    async getMenuListByUid(uid) {
        let sql = `
            select a.name, a.path
            from user as u
            join r_user_role as rur on u.id = rur.uid
            join r_role_acl as rra on rur.rid = rra.rid
            join acl as a on rra.aid = a.id and a.type = 'front'
            where u.id = ?
        `;
        let params = [uid];
        let res = await this.app.mysql.query(sql, params);
        return res;
    }

    /**
     * 根据用户id，获取用户的角色信息
     * @param {number} uid 用户id
     */
    async getRoleByUid(uid) {
        let sql = `
            select rur.rid, r.name as rname
            from role as r
            join r_user_role as rur on rur.rid = r.id
            where rur.uid = ?
        `;
        let params = [uid];
        let res = await this.app.mysql.query(sql, params);
        return res[0];
    }
}

module.exports = UserService;
